package com.jrzh.mvc.service.sys.impl;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jrzh.common.cache.Cache;
import com.jrzh.common.cache.CacheManager;
import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.tools.JsonTools;
import com.jrzh.common.utils.ReflectUtils;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.framework.base.repository.BaseRepository;
import com.jrzh.framework.base.service.impl.BaseServiceImpl;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.mvc.constants.CacheConstants;
import com.jrzh.mvc.convert.sys.ConfigConvert;
import com.jrzh.mvc.model.sys.ConfigModel;
import com.jrzh.mvc.repository.sys.ConfigRepository;
import com.jrzh.mvc.search.sys.ConfigSearch;
import com.jrzh.mvc.service.sys.ConfigServiceI;
import com.jrzh.mvc.view.sys.ConfigView;

@Service("configService")
@SuppressWarnings("all")
public class ConfigServiceImpl extends BaseServiceImpl<ConfigModel, ConfigSearch, ConfigView> implements ConfigServiceI{
	
	@Autowired
	private ConfigRepository configRepository;
	
	@Autowired
	private ConfigConvert configConvert;
	
	@Override
	public BaseRepository<ConfigModel, Serializable> getDao() {
		return configRepository;
	}
	@Override
	public BaseConvertI<ConfigModel, ConfigView> getConvert() {
		return configConvert;
	}

	public void initCache() throws ProjectException {
		CacheManager.clearOnly(CacheConstants.CONFIG_KEY);
		List<ConfigView> list = this.findAllView();
		Map<String, String> map = new HashMap<String, String>();
		if(CollectionTools.isNotBlank(list)){
			for(ConfigView view : list){
				map.put(view.getKey(), view.getValue());
			}
		}
		Cache cache = new Cache();
		cache.setKey(CacheConstants.CONFIG_KEY);
		cache.setValue(map);
		CacheManager.putCache(CacheConstants.CONFIG_KEY, cache);
	}
	

	public String getValue(String key) throws ProjectException {
		Cache cache = CacheManager.getCacheInfo(CacheConstants.CONFIG_KEY);
		if(null == cache){
			initCache();
			cache = CacheManager.getCacheInfo(CacheConstants.CONFIG_KEY);
		}
		Map<String, String> cofigMap = (Map<String, String>) cache.getValue();
		return cofigMap.get(key);
	}

	public void refreshCache(String key, String value) throws ProjectException {
		Cache cache = CacheManager.getCacheInfo(CacheConstants.CONFIG_KEY);
		if(null != cache){
			Map<String, String> map = (Map)cache.getValue();
			if(null != map){
				CacheManager.clearOnly(CacheConstants.CONFIG_KEY);
				map.put(key, value);
				cache.setValue(map);
				CacheManager.putCache(CacheConstants.CONFIG_KEY, cache);
			}else{
				initCache();
			}
		}else{
			initCache();
		}
	}

	@Override
	public void saveInit(String project, InputStream in) throws ProjectException {
		log.info("###########同步"+ project  +"模块 配置表数据 Begin");
		JSONArray array = JsonTools.getFromFile(in);
		List<String> inKeys = new ArrayList<String>();
		if(null != array && array.size() > 0){
			for(int i = 0; i < array.size(); i ++){
				JSONObject jsonObject = array.getJSONObject(i);
				ConfigModel model = new ConfigModel();
				String group = jsonObject.getString("group");
				String name = jsonObject.getString("name");
				String key = jsonObject.getString("key");
				String value = jsonObject.getString("value");
				String dataType = jsonObject.getString("dataType");
				inKeys.add(key);
				model.setGroup(group);
				model.setName(name);
				model.setKey(key);
				model.setValue(value);
				model.setDataType(dataType);
				ConfigModel dbm = this.findByField("key", key);
				if(null == dbm){
					log.info("######新增" + model.getKey());
					this.add(model, SessionUser.getSystemUser());
				}
				/*else{
					if(!equals(dbm, model)){
						log.info("######编辑" + model.getKey());
						ReflectUtils.copySameFieldToTargetFilterNull(model, dbm);
						this.edit(dbm, SessionUser.getSystemUser());
					}
				}*/
			}
			/*//处理删除的数据
			ConfigSearch search = new ConfigSearch();
			search.setLikeKey(project);
			search.setNotInKeys(inKeys.toArray(new String[]{}));
			List<ConfigModel> list = this.list(search);
			if(CollectionTools.isNotBlank(list)){
				for(ConfigModel m : list){
					this.delete(m.getId(), SessionUser.getSystemUser());
				}
			}*/
		}
		log.info("###########同步"+project+"模块 配置表数据 End");
	}
	
	private Boolean equals(ConfigModel source, ConfigModel target) {
		return StringUtils.equals(source.getGroup(), target.getGroup()) &&
				   StringUtils.equals(source.getName(), target.getName()) &&
				   StringUtils.equals(source.getValue(), target.getValue()) &&
				   StringUtils.equals(source.getDataType(), target.getDataType());
	}
	
	
	@Override
	public List<ConfigView> treegrid() throws ProjectException {
		List<ConfigModel> list = this.findAll();
		Map<String, String> groupMaps = new HashMap<String, String>();
		List<ConfigView> configList = new ArrayList<ConfigView>();
		for(ConfigModel model : list){
			groupMaps.put(model.getGroup(), "");
		}
		for(String group : groupMaps.keySet()){
			ConfigView groupConfig = new ConfigView();
			List<ConfigView> groupList = new ArrayList<ConfigView>();
			for(ConfigModel config : list){
				if(StringUtils.equals(config.getGroup(), group)){ 
					groupList.add(configConvert.convertToView(config));
				}
			}
			groupConfig.setGroup(group);
			groupConfig.setGroupList(groupList);
			configList.add(groupConfig);
		}
		return configConvert.convertToTreeGrid(configList);
	}

}
